<?php
namespace common\services;

use Yii;
use common\base\BaseActiveRecord;
use common\helpers\TStringHelper;
use common\models\Exhibition;
use common\models\ExhibitionHall;
use common\models\UserFollow;
use common\models\UserHistory;
use yii\data\ActiveDataProvider;
use yii\data\Pagination;
use yii\helpers\ArrayHelper;
use yii\web\Cookie;
use yii\web\NotFoundHttpException;

class ExhibitionServices extends Exhibition
{

    /**
     * 展会
     * @param $params
     * @return array
     */
    public function search($params){
        $model = Exhibition::find(false);
        $model->orderBy('id desc');

        $dataProvider = new ActiveDataProvider([
            'query' => $model,
            'pagination' => [
                'pagesize' => $params['defaultPageSize'],
            ]
        ]);

        if (isset($params['region_id']) && $params['region_id'] != '') {
            $model->andFilterWhere(['=', 'region_id', $params['region_id']]);
        }
        if (isset($params['recommend']) && $params['recommend'] != '') {
            $model->andFilterWhere(['=', 'recommend', $params['recommend']]);
        }
        if (isset($params['status']) && $params['status'] != '') {
            $model->andFilterWhere(['=', 'status', $params['status']]);
        }

        if (!empty($params['keywords'])){
            $model->andFilterWhere(['or', ['like', 'title', $params['keywords']], ['like', 'introduce', $params['keywords']], ['like', 'address', $this->address]]);
        }

        //$sql = $model->createCommand()->getRawSql();

        return $dataProvider;
    }

    /**
     * 展会列表
     * @param array $params
     * @return array
     */
    public function searchPage($params = array()){
        $model = Exhibition::find(false)
            ->andFilterWhere(['=', 'status', self::STATUS_FLAG_NORMAL]);

        if (!empty($params['category_id'])){
            $model->andFilterWhere(['=', 'category_id', $params['category_id']]);
        }
        if (!empty($params['hall_id'])){
            $model->andFilterWhere(['=', 'hall_id', $params['hall_id']]);
        }

        if (!empty($params['starttime'])) {
            $model->andFilterWhere(['>' , 'starttime', strtotime($params['starttime'])]);
        }
        if (!empty($params['endtime'])) {
            $model->andFilterWhere(['<', 'endtime', strtotime($params['endtime'])+86399]);
        }

        if (!empty($params['hot'])){
            $model->andFilterWhere(['=', 'hot', $params['hot']]);
        }

        if (!empty($params['city'])) {
            $city = $params['city'];
            if (strpos($city, ',')) {
                $city = explode(',', $city);
                $model->andFilterWhere(['in', 'city', $city]);
            }else{
                $model->andFilterWhere(['=', 'city', $city]);
            }
        }

        if (isset($params['recommend'])){
            $model->andFilterWhere(['=', 'recommend', $params['recommend']]);
        }
        //自带查询条件
        if (!empty($params['where']) && is_array($params['where'])) {
            $model->andFilterWhere($params['where']);
        }

        if (!empty($params['over'])) {
            $model->andFilterWhere(['<', 'endtime', time()]);
        }

        if (!empty($params['keywords'])){
            $model->andFilterWhere(['or', ['like', 'title', $params['keywords']], ['like', 'introduce', $params['keywords']], ['like', 'scope', $params['keywords']], ['like', 'booth_info', $params['keywords']]]);
        }

        $count = $model->count(1);

        if ($count > 0){

            $sort = isset($params['sort']) ? $params['sort'] : 'DESC';
            $order = !empty($params['order']) ? (!is_array($params['order']) ? array($params['order'] =>($sort == 'DESC' ? SORT_DESC : SORT_ASC)) : $params['order']) : array('order' => SORT_DESC, 'id' => SORT_DESC);

            if (isset($params['ajax'])){
                $limit = $params['limit'] ? $params['limit'] : 6;
                $data = $model->select('id,title,logo,hall_title,category_id,city,starttime,endtime,wechat_qrcode,litpic,logo')->asArray()->orderBy($order)->limit($limit)->all();
                $page = null;
            }else {
                $page = new Pagination(['defaultPageSize' => $params['defaultPageSize'], 'totalCount' => $count]);
                $data = $model->orderBy($order)->offset($page->offset)->limit($page->limit)->asArray()->all();
            }
        }else{
            $page = $data = null;
        }

        if (!empty($data)) {
            $categoryService = new ExhibitionCategoryServices();
            $userId = Yii::$app->user->getId();
            $followService = new UserFollowServices();
            foreach ($data as $key => &$val) {
                $starttime = $val['starttime'];
                $endtime = $val['endtime'];
                if (date('Y', $starttime) == date('Y', $endtime)) {
                    $val['show_start'] = date('Y-m-d', $starttime);
                    $val['show_end'] = date('m-d', $endtime);
                }else{
                    $val['show_start'] = date('Y-m-d', $starttime);
                    $val['show_end'] = date('Y-m-d', $endtime);
                }
                $category = $categoryService->getDataByCategoryId($val['category_id']);
                if (!empty($category)){
                    $val['category_name'] = $category['name'];
                }
                //判断当前登录用户是否关注
                if (!empty($userId)) {
                    $val['is_follow'] = $followService->isFollow($userId, UserFollow::USER_FOLLOW_TYPE_EXHIBITION, $val['id']);
                }else{
                    $val['is_follow'] = 0;
                }
            }
        }

        return ['data' => $data, 'page' => $page];
    }

    /**
     * 展会详情
     * @param $id
     * @return mixed|null|static
     */
    public function getDetail($id) {
        $model = Exhibition::findOne($id);

        if (empty($model)) {
            throw new NotFoundHttpException('The requested page does not exist.');
        }

        $data = array(
            'model' => $model,
        );

        $starttime = $model->starttime;
        $endtime =  $model->endtime;
        if (date('Y', $starttime) == date('Y', $endtime)) {
             $data['show_start'] = date('Y年m月d日', $starttime);
            $data['show_end'] = date('m月d日', $endtime);
        }else{
           $data['show_start'] = date('Y年m月d日', $starttime);
           $data['show_end'] = date('Y年m月d日', $endtime);
        }
        //时间判断
        $time = time();
        $diff  = ceil(($starttime - time()) / 86400);
        if ($time > $starttime && $time < $endtime) {
            $diff = 0;
        }
        $data['diff_time'] = $diff;

        //展馆信息
        $hall = ExhibitionHall::findOne($model->hall_id)->toArray();
        $data['hall'] = array(
            'lat' => $hall['lat'],
            'lng' => $hall['lng'],
        );

        return $data;
    }

    /**
     * 获取登录用户浏览历史
     * @param $userId
     * @return array|\yii\db\ActiveRecord[]
     */
    public function getUserHistoryByUserId($userId) {
        $historyService = new UserHistoryServices();
        $history = $historyService->getUserInterestByUserId(UserHistory::USER_HISTORY_TYPE_EXHIBITION, $userId);
        $res = array();
        if (!empty($history)) {
            $object = ArrayHelper::map($history, 'id', 'object_id');
            $objectId = array_values($object);
            if (!empty($objectId)) {
                $model = Exhibition::find(false);
                $model->andFilterWhere(['=', 'status', Exhibition::STATUS_FLAG_NORMAL]);
                $model->andFilterWhere(['in', 'id', $objectId]);
                $res = $model->select('id,title,logo,hall_id,hall_title,category_id,city,starttime,endtime,wechat_qrcode,litpic,logo')->asArray()->orderBy("endtime desc,order desc")->limit(24)->all();
                foreach ($res as $key => &$val) {
                    $starttime = $val['starttime'];
                    $endtime = $val['endtime'];
                    if (date('Y', $starttime) == date('Y', $endtime)) {
                        $val['show_start'] = date('Y-m-d', $starttime);
                        $val['show_end'] = date('m-d', $endtime);
                    } else {
                        $val['show_start'] = date('Y-m-d', $starttime);
                        $val['show_end'] = date('Y-m-d', $endtime);
                    }
                }
            }
        }
        return $res;
    }

    /**
     * 获取用户感兴趣的展会
     * @param string $userId
     */
    public function getUserInterestByUserId($userId = '', $limit = 24) {
        $historyService = new UserHistoryServices();
        $history = $historyService->getUserInterestByUserId(UserHistory::USER_HISTORY_TYPE_EXHIBITION, $userId);
        $objectId = array();
        if (!empty($history)) {
            $object = ArrayHelper::map($history, 'id', 'object_id');
            $objectId = array_values($object);
        }
        $model = Exhibition::find(false);
        $model->andFilterWhere(['=', 'status', Exhibition::STATUS_FLAG_NORMAL]);
        if (!empty($objectId)) {
            $model->andFilterWhere(['in', 'id', $objectId]);
        }
        $related = $model->asArray()->select('id,tags')->all();
        $relatedTags = array();
        if (!empty($related)) {
            $relatedTags = ArrayHelper::map($related, 'id', 'tags');
            $relatedTags = array_values($relatedTags);
            $relatedTags = join(',', $relatedTags);
            $relatedTags = explode(',', $relatedTags);
            $relatedTags = array_filter($relatedTags);
            $relatedTags = array_unique($relatedTags);
        }

        $model = Exhibition::find(false);
        $model->andFilterWhere(['=', 'status', Exhibition::STATUS_FLAG_NORMAL]);
        //先根据标签查询，再根据ID来查询
        if (!empty($relatedTags)){
            $model->andFilterWhere(['like', 'tags', $relatedTags]);
        }/*else{
            if (!empty($objectId)) {
                $model->andFilterWhere(['in', 'id', $objectId]);
            }
        }*/

        $data = $model->select('id,title,logo,hall_id,hall_title,category_id,city,starttime,endtime,wechat_qrcode,litpic,logo')->asArray()->orderBy("endtime desc,order desc")->limit($limit)->all();
        if (!empty($data)) {
            foreach ($data as $key => &$val) {
                $starttime = $val['starttime'];
                $endtime = $val['endtime'];
                if (date('Y', $starttime) == date('Y', $endtime)) {
                    $val['show_start'] = date('Y-m-d', $starttime);
                    $val['show_end'] = date('m-d', $endtime);
                } else {
                    $val['show_start'] = date('Y-m-d', $starttime);
                    $val['show_end'] = date('Y-m-d', $endtime);
                }
            }
        }
        return $data;
    }

    /**
     * 返回关注列表
     * @param $userId
     * @param int $limit
     * @return array|\yii\db\ActiveRecord[]
     */
    public function getMyFollowList($userId, $objectType = UserFollow::USER_FOLLOW_TYPE_EXHIBITION, $limit = 12){
        $userFollowService = new UserFollowServices();
        $list = $userFollowService->getMyFollow($userId, $objectType, $limit);
        if (empty($list)) {
            return array();
        }
        $exhibitionArray = ArrayHelper::map($list, 'id', 'object_id');
        $idArray = array_values($exhibitionArray);
        $idArray = array_unique($idArray);
        $model = Exhibition::find(false);
        $model->andFilterWhere(['=', 'status', Exhibition::STATUS_FLAG_NORMAL])
            ->andFilterWhere(['in', 'id', $idArray]);

        $result = $model->asArray()->limit($limit)->all();
        if (!empty($result)){
            foreach ($result as $key => &$val) {
                $starttime = $val['starttime'];
                $endtime = $val['endtime'];
                if (date('Y', $starttime) == date('Y', $endtime)) {
                    $val['show_start'] = date('Y-m-d', $starttime);
                    $val['show_end'] = date('m-d', $endtime);
                } else {
                    $val['show_start'] = date('Y-m-d', $starttime);
                    $val['show_end'] = date('Y-m-d', $endtime);
                }
            }
        }
        return $result;
    }

    /**
     * 查询用户关注的展会数据
     * @param array $params
     * @return array
     */
    public function searchUserFollow($params = array()){
        $model = UserFollow::find(false);
        $tablename = UserFollow::tableName();
        $model->andFilterWhere(['=', $tablename.'.status', UserFollow::STATUS_FLAG_NORMAL])
            ->andFilterWhere(['=', $tablename.'.type', UserFollow::USER_FOLLOW_TYPE_EXHIBITION]);
        if (!empty($params['user_id'])) {
            $model->andFilterWhere(['=', $tablename.'.user_id', $params['user_id']]);
        }

        $model->leftJoin(Exhibition::tableName()." as b", $tablename.".object_id=b.id");
        $model->andFilterWhere(['=', 'b.status', Exhibition::STATUS_FLAG_NORMAL]);

        $count = $model->count(1);

        if ($count > 0) {
            $model->select("b.*");
            $page = new Pagination(['defaultPageSize' => $params['defaultPageSize'], 'totalCount' => $count]);
            $data = $model->orderBy($tablename.".id desc")->offset($page->offset)->limit($page->limit)->asArray()->all();
            foreach ($data as $key => &$val) {
                $starttime = $val['starttime'];
                $endtime = $val['endtime'];
                if (date('Y', $starttime) == date('Y', $endtime)) {
                    $val['show_start'] = date('Y-m-d', $starttime);
                    $val['show_end'] = date('m-d', $endtime);
                } else {
                    $val['show_start'] = date('Y-m-d', $starttime);
                    $val['show_end'] = date('Y-m-d', $endtime);
                }
            }
        }else{
            $data = $page = null;
        }
        return ['data' => $data, 'page' => $page];
    }

    /**
     * 查询用户浏览展会数据
     * @param array $params
     * @return array
     */
    public function searchUserHistory($params = array()){
        $model = UserHistory::find(false);
        $tablename = UserHistory::tableName();
        $model->andFilterWhere(['=', $tablename.'.status', UserHistory::STATUS_FLAG_NORMAL])
            ->andFilterWhere(['=', $tablename.'.object_type', UserHistory::USER_HISTORY_TYPE_EXHIBITION]);
        if (!empty($params['user_id'])) {
            $model->andFilterWhere(['=', $tablename.'.user_id', $params['user_id']]);
        }

        $model->leftJoin(Exhibition::tableName()." as b", $tablename.".object_id=b.id");
        $model->andFilterWhere(['=', 'b.status', Exhibition::STATUS_FLAG_NORMAL]);

        $count = $model->count(1);

        if ($count > 0) {
            $model->select("b.*");
            $page = new Pagination(['defaultPageSize' => $params['defaultPageSize'], 'totalCount' => $count]);
            $data = $model->orderBy($tablename.".id desc")->offset($page->offset)->limit($page->limit)->asArray()->all();
            foreach ($data as $key => &$val) {
                $starttime = $val['starttime'];
                $endtime = $val['endtime'];
                if (date('Y', $starttime) == date('Y', $endtime)) {
                    $val['show_start'] = date('Y-m-d', $starttime);
                    $val['show_end'] = date('m-d', $endtime);
                } else {
                    $val['show_start'] = date('Y-m-d', $starttime);
                    $val['show_end'] = date('Y-m-d', $endtime);
                }
            }
        }else{
            $data = $page = null;
        }
        return ['data' => $data, 'page' => $page];
    }

    /**
     * 同期展会
     * @param $exhibition_id
     * @return array|\yii\db\ActiveRecord[]
     */
    public function getExhibitionSame($exhibition_id) {
        $data = Exhibition::findOne($exhibition_id);

        $model = Exhibition::find(false);
        $model->andFilterWhere(['=', 'status', Exhibition::STATUS_FLAG_NORMAL])
            ->andFilterWhere(['<>', 'id', $exhibition_id])
            ->andFilterWhere(['>=', 'starttime', $data->starttime])
            ->andFilterWhere(['<=', 'endtime', $data->endtime]);

        $res = $model->select('id,title,litpic')->orderBy('order desc,id desc')->limit(3)->asArray()->all();

        if (empty($res)) {
            $res = Exhibition::find(false)->andFilterWhere(['<>', 'id', $exhibition_id])->andFilterWhere(['=', 'status', Exhibition::STATUS_FLAG_NORMAL])->select('id,title,litpic')->orderBy('order desc,id desc')->limit(3)->asArray()->all();
        }

        return $res;
    }

    /**
     * 按月返回所在年份展馆的展会
     * @param $hall_id
     * @return array
     */
    public function getHallExhibitionByHallId($hall_id, $year = '') {
        $model = Exhibition::find(false);
        $year = empty($year) ? date('Y') : $year;
        $model->andFilterWhere(['=', 'status', Exhibition::STATUS_FLAG_NORMAL])
            ->where("FROM_UNIXTIME(`starttime`, '%Y')=$year")
            ->andFilterWhere(['=', 'hall_id', $hall_id])
            ->select('id, title, starttime, endtime')
            ->asArray()
            ->orderBy('order desc, id desc');

        $list = $model->all();

        $res = array();
        if (!empty($list)) {
            foreach ($list as $val) {
                $k = date('m', $val['starttime']);
                $res[$k][] = $val;
            }
        }

        return $res;
    }

    /**
     * 查询展馆最近一次展会
     * @param $hall_id
     * @return array|\yii\db\ActiveRecord[]
     */
    public function getNearExhibitionByHallId($hall_id) {
        $model = Exhibition::find(false);
        $model->andFilterWhere(['=', 'status', Exhibition::STATUS_FLAG_NORMAL])
            ->andFilterWhere(['=', 'hall_id', $hall_id])
            ->orderBy('starttime desc, order desc, id desc')
            ->select('id,title,starttime,endtime')
            ->limit(1);

        return $model->asArray()->all();
    }

    /**
     * 添加数据到对比中
     * @param $exhibition_id
     * @return array|mixed
     */
    public function addCompareExhibition($exhibition_id) {
        $cacheKey = 'compare_'.Yii::$app->session->getId();
        $setCookie = Yii::$app->response->cookies;//设置cookie
        $getCookie = Yii::$app->request->cookies;//获取cookie

        $result = [];
        if (isset($getCookie[$cacheKey])) {
            $result = $getCookie[$cacheKey]->value;
        }
        //判断是否存在
        if (!empty($result)) {
            $key = array_keys($result);
            if (in_array($exhibition_id, $key)) {
                unset($result["$exhibition_id"]);
            }else{
                if (count($result) >=3 ){
                    return ['code' => -1, 'data' => $result, 'msg' => Yii::t('frontend', 'max_select_exhibition')];
                }
                $model = Exhibition::findOne($exhibition_id);
                $result[$exhibition_id] = $model->title;
                //数组首插入数据
                //array_unshift($result, array("$exhibition_id" => array('id' => $model->id, 'name' => $model->title)));
            }
        }else{
            $model = Exhibition::findOne($exhibition_id);
            $result[$exhibition_id] = $model->title;
            //数组首插入数据
            //array_unshift($result, array("$exhibition_id" => array('id' => $model->id, 'name' => $model->title)));
        }
        //删除3个数组以上的数据
        if (count($result) > 3) {
            array_splice($result, 3);
        }

        //保存数据到cookie
        if (!empty($result)) {
            $setCookie->add(new \yii\web\Cookie([
                'name' => $cacheKey,
                'value' => $result,
                'expire' => time() + 86400*30,
            ]));
        }else{
            //无数则清除
            $setCookie->remove($cacheKey);
        }

        return ['code' => 0, 'data' => $result, 'msg' => 'ok'];
    }

    /**
     * 获取对比数据
     * @return array|mixed
     */
    public function getCompareExhibition() {
        $cacheKey = 'compare_'.Yii::$app->session->getId();
        $getCookie = Yii::$app->request->cookies;//获取cookie
        $result = [];
        if (isset($getCookie[$cacheKey])) {
            $result = $getCookie[$cacheKey]->value;
        }
        return ['code' => 0, 'data' => $result, 'msg' => 'ok'];
    }

    /**
     * 清空对比数据
     * @return array
     */
    public function removeCompareExhibition(){
        $cacheKey = 'compare_'.Yii::$app->session->getId();
        $setCookie = Yii::$app->response->cookies;//设置cookie
        $setCookie->remove($cacheKey);

        return [];
    }

    /**
     * 获取展会数据
     * @return array|\yii\db\ActiveRecord[]
     */
    public function getCompareData(){
        $array = $this->getCompareExhibition();
        if (empty($array['data'])) {
            return [];
        }
        $exhibitionId = array_keys($array['data']);
        $model = Exhibition::find(false)
            ->andFilterWhere(['=', 'status', Exhibition::STATUS_FLAG_NORMAL])
            ->andFilterWhere(['in', 'id', $exhibitionId])
            ->asArray()
            ->all();

        if (!empty($model)) {
            $exhibitionExhubitorService = new ExhibitionExhibitorServices();
            foreach ($model as &$val) {
                //知名展商
                $exhibitor = $exhibitionExhubitorService->getExhibitorsByExhibitionId($val['id']);
                if (!empty($exhibitor)) {
                    $exhibitorName = ArrayHelper::map($exhibitor, 'exhibitor_id', 'name');
                    $val['exhibitor'] = join("<br />", $exhibitorName);
                }else{
                    $val['exhibitor'] = '';
                }
            }
        }

        return $model;
    }

    /**
     * 导入数据
     * @param $fileUrl
     * @return int
     */
    public function importData($fileUrl, &$errMsg = '') {
        $filePath = Yii::$app->basePath.'/..'.$fileUrl;
        if (!$filePath) {
            return -1;//文件不存在
        }
        require_once dirname(dirname(__FILE__)).'/components/PHPExcel/PHPExcel.php';
        //$PHPExcel = new \PHPExcel();
        $PHPReader = new \PHPExcel_Reader_Excel2007();
        if (!$PHPReader->canRead($filePath)) {
            $PHPReader = new \PHPExcel_Reader_Excel5();
            if (!$PHPReader->canRead($filePath)) {
                $PHPReader = new \PHPExcel_Reader_CSV($filePath);
                if (!$PHPReader->canRead($filePath)) {
                    return -2; //文件读取失败
                }
            }
        }
        $PHPExcel = $PHPReader->load($filePath); // 文档名称
        $objWorksheet = $PHPExcel->getSheet(0);
        $highestRow = $objWorksheet->getHighestRow(); // 取得总行数
        if ($highestRow < 2) {
            return -3;//未读取到有效数据
        }
        //$highestColumn = $objWorksheet->getHighestColumn(); // 取得总列数
        $res = array();
        $sheet_0 = $objWorksheet->toArray();
        foreach ($sheet_0 as $k => $val) {
            if ($k > 0 && !empty($val[0])) {
                $res[$k] = $val;
            }
        }
        $count = 0;
        if (!empty($res)) {
            $batchInsert = [];
            $exhibitionHallService = new ExhibitionHallServices();
            $exhibitionCategoryService = new ExhibitionCategoryServices();
            $exhibitionExhibitorService = new ExhibitionExhibitorServices();
            $exhibitionPictureService = new ExhibitionPictureServices();
            $systemService = new SystemServices();
            //默认logo
            $defaultLogo = $systemService->getSys('default_zhanhui_logo');
            //默认背景
            $defaultBg = $systemService->getSys('default_zhanhui_bg');
            //默认二维码
            $defaultQrcode = $systemService->getSys('default_zhanhui_qrcode');
            //默认封面
            $defaultLitpic = $systemService->getSys('default_zhanhui_litpic');
            if (!empty($defaultLitpic) && !empty($defaultLitpic['value'])) {
                $litpic = $defaultLitpic['value'];
                $path = Yii::$app->basePath.'/..'.$litpic;
                if (file_exists($litpic)) {
                    if (!file_exists($path.'_350x210.jpg')){
                        TStringHelper::getImageThumbs($litpic, 350, 210);
                    }
                    if (!file_exists($path.'_305x190.jpg')){
                        TStringHelper::getImageThumbs($litpic, 305, 190);
                    }
                    if (!file_exists($path.'_250x150.jpg')){
                        TStringHelper::getImageThumbs($litpic, 250, 150);
                    }
                    if (!file_exists($path.'_184x150.jpg')){
                        TStringHelper::getImageThumbs($litpic, 184, 150);
                    }
                    if (!file_exists($path.'_86x75.jpg')){
                        TStringHelper::getImageThumbs($litpic, 86, 75);
                    }
                }

            }

            foreach ($res as $k => $v) {
                $title = trim($v[0]);
                //if (empty($title)) break;
                $time = explode('-', $v[1]);
                //if (empty($time[0]) || empty($time[1])) continue;
                $hall_title = $v[2];
                //if (empty($hall_title)) continue;
                $hall = $exhibitionHallService->getHallInfoByTitle($hall_title);
                //if (empty($hall)) continue;
                $categoryTitle = $v[3];
                //if (empty($categoryTitle)) continue;
                $category = $exhibitionCategoryService->getCategoryByTitle($categoryTitle);
                //if (empty($category)) continue;
                $introduce = $v[6];
                $scope = $v[7];
                $sponsor = $v[8];
                $undertook = $v[9];
                $exhibitor = $v[10];
                $area = $v[13];
                //if ($area == '') continue;
                $address = $v[14];
                //if (empty($address)) continue;
                $audience_number = $v[15];
                //if ($audience_number == '') continue;
                $business_number = $v[16];
                //if ($business_number == '') continue;
                $website = $v[17];
                //if (empty($website)) continue;
                $build_number = $v[18];
                //if ($build_number == '') continue;
                $booth_info = $v[19];
                //if (empty($booth_info)) continue;

                $model = new Exhibition();
                $model->title = $title;
                $model->starttime = strtotime($time[0]);
                $model->endtime = strtotime(date('Y-m-d 23:59:59', strtotime($time[1])));
                $model->hall_id = $hall['id'];
                $model->hall_title = $hall_title;
                $model->category_id = $category['id'];
                $model->introduce = $introduce;
                $model->scope = $scope;
                $model->sponsor = $sponsor;
                $model->undertook = $undertook;
                $model->area = (string)$area;
                $model->address = $address;
                $model->audience_number = $audience_number;
                $model->business_number = $business_number;
                $model->build_number = $build_number;
                $model->website = $website;
                $model->booth_info = $booth_info;
                $model->hot = 5;

                //默认值设置
                //logo
                $logo = isset($v[20]) ? $v[20] : null;
                if (empty($logo)) {
                    $model->logo = !empty($defaultLogo) ? $defaultLogo['value'] : '';
                }else{
                    $model->logo = $logo;
                }
                //封面
                $litpic = isset($v[21]) ? $v[21] : null;
                if (empty($litpic)) {
                    $model->litpic = !empty($defaultLitpic) ? $defaultLitpic['value'] : '';
                }else{
                    $path = Yii::$app->basePath.'/..'.$litpic;
                    if (file_exists($litpic)) {
                        if (!file_exists($path.'_350x210.jpg')){
                            TStringHelper::getImageThumbs($litpic, 350, 210);
                        }
                        if (!file_exists($path.'_305x190.jpg')){
                            TStringHelper::getImageThumbs($litpic, 305, 190);
                        }
                        if (!file_exists($path.'_250x150.jpg')){
                            TStringHelper::getImageThumbs($litpic, 250, 150);
                        }
                        if (!file_exists($path.'_184x150.jpg')){
                            TStringHelper::getImageThumbs($litpic, 184, 150);
                        }
                        if (!file_exists($path.'_86x75.jpg')){
                            TStringHelper::getImageThumbs($litpic, 86, 75);
                        }
                    }
                    $model->litpic = $litpic;
                }
                //背景
                $bg = isset($v[22]) ? $v[22] : null;
                if (empty($bg)) {
                    $model->bg = !empty($defaultBg) ? $defaultBg['value'] : '';
                }else{
                    $model->bg = $bg;
                }

                $model->wechat_qrcode = !empty($defaultQrcode) ? $defaultQrcode['value'] : '';

                if ($model->save()) {
                    $count ++;
                    if (!empty($exhibitor)) {
                        //添加展商
                        $exhibitionExhibitorService->addExhibitionExhibitor($model->id, $exhibitor);
                    }
                    //展会锦集
                    if (!empty($v[23])) {
                        $picture = explode(';', $v[23]);
                        $exhibitionPictureService->setExhibitionPicture($model->id, $picture);
                    }

                }else{
//                    print_r($model->getFirstErrors());
                    $errMsg .= "第".($k+1)."行：".join("", $model->getFirstErrors())."<br />";
                    continue;
                }
                //array_push($batchInsert, $model);
            }
            //return $msg;
            //批量添加数据
            if (!empty($batchInsert) ) {
                //BaseActiveRecord::batchInsertSqlArray($batchInsert);
            }
        }
        return $count;
    }

    /**
     * 判断当前月份是否有展会进行
     * @param $month
     * @return int
     */
    public function getMonthCount($month){
        $model = Exhibition::find(false);
        $model->andFilterWhere(['=', 'status', Exhibition::STATUS_FLAG_NORMAL]);

        $start_time = strtotime(date("Y-$month-01"));
        $end_time = strtotime(date("Y-m-d 23:59:59", mktime(0, 0, 0, $month+1,1)-1));

        $model->where("(starttime > $start_time && starttime < $end_time) or (endtime > $start_time && endtime < $end_time)");

        $count = $model->count(1);

        return intval($count);
    }

}
